<?php
/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2022/1/14
 * Time: 2:40 下午
 * description: User.php
 * 用户有关业务逻辑
 */

namespace app\home\business;


use think\Exception;
use think\facade\Cache;

class User
{
    /**
     * 用户注册
     * @param $params
     * @return \app\common\model\User|\think\Model
     * @throws Exception
     */
    public  static function register($params){
        # 验证验证码
        $user_code = $params['code'];
        $cache_code = Cache::get('register_code_'.$params['phone']);
        if ($user_code != $cache_code) {
            throw new Exception("验证码错误");
        }
        # 验证通过后、删除缓存
        Cache::delete('register_code_'.$params['phone']);

        return \app\common\model\User::create([
            'username' => md5($params['phone']),
            'nickname' => "品优购".$params['phone'],
            'phone' => $params['phone'],
            'password' => encrypt_password($params['password']),
        ]);
    }

    /**
     * 登录功能
     * @param $phone
     * @param $password
     * @return bool
     * @throws Exception
     */
    public static function doLogin($phone,$password){
        # 第一步查数据是否存在手机号
        $info = \app\common\model\User::where([
            'phone' => $phone,
            'password' => encrypt_password($password),# 加密验证
        ])->field('id,username,nickname,phone')->find();
        if ($info) {
            session('user_info',$info);
//            //迁移cookie购物车数据到数据表
//            Cart::cookieToDb();
            return  true;
        }else {
            throw new Exception('帐号或密码不存在');
        }
    }

    /**
     * @param $user_info
     * @param $open_id
     * @return bool
     * @throws Exception
     */
    public static function createUser($user_info,$open_id){
        # 判断库里是否有唯一的open_id
        $is_user_info = \app\common\model\User::where('openid',$open_id)->find()->toArray();
        if ($is_user_info) {
            session('user_info',$is_user_info);
        } else {
            # 新添加数据
            $user_info = \app\common\model\User::create([
                'username'  => '',
                'nickname' => $user_info['nickname'],
                'phone' => 0,
                'password' => encrypt_password(123456),
                'figure_url' => $user_info['figureurl'],
                'email' => '',
                'open_type' => 'qq',
                'openid' => $open_id,
            ]);
            session('user_info',$user_info->toArray());
        }
        return true;

    }
}